//
//  UITabBar+badge.m
//  
//
//  Created by guoshiqing on 16/4/2.
//  Copyright © 2016年\
//

#import "UITabBar+badge.h"

#define TabbarItemNums 5.0    //tabbar的数量 如果是5个设置为5.0

@implementation UITabBar (badge)

//显示小红点
- (void)showBadgeOnItemIndex:(NSInteger)index{
    
    // 如果小红点不存在，就新建小红点，如果已经存在就显示出来
    if (![self isExistBadgeOnItemIndex:index]) {
        //新建小红点
        UIView *badgeView = [[UIView alloc]init];
        badgeView.tag = 10+index;
        badgeView.layer.cornerRadius = 4.5f;//圆形
        badgeView.backgroundColor = [UIColor redColor];//颜色：红色
        CGRect tabFrame = self.frame;
        
        //确定小红点的位置(这里的index要按顺序来)
        float percentX = (index + 0.65) / TabbarItemNums;
        CGFloat x = ceilf(percentX * tabFrame.size.width);
        CGFloat y = ceilf(0.1 * tabFrame.size.height);
        badgeView.frame = CGRectMake(x, y, 9.f, 9.f);//圆形大小为10
        [self addSubview:badgeView];
    }
}

//隐藏小红点
- (void)hideBadgeOnItemIndex:(NSInteger)index{
    
    //按照tag值进行隐藏
    for (UIView *subView in self.subviews) {
        if (subView.tag == 10+index) {
            subView.hidden = YES;
        }
    }
}

// 查找小红点是否存在，并设置为显示
- (BOOL)isExistBadgeOnItemIndex:(NSInteger)index
{
    //按照tag值进行移除
    for (UIView *subView in self.subviews) {
        if (subView.tag == 10+index) {
            subView.hidden = NO;
            return YES;
        }
    }
    return NO;
}

@end
